package com.example.rabbitmqdemo.hellorabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.concurrent.TimeoutException;

public class RabbitMQProducer {
    private static final String EXEHANGE_NAME = "exchange_demo";
    private static final String ROUTING_KEY = "routingkey_demo";
    private static final String QUEUE_NAME = "queue_demo";
    private static final String IP_ADDRESS = "192.168.137.2";
    private static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException {
        // 生成连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(IP_ADDRESS);
        factory.setPort(PORT);
        factory.setVirtualHost("/");
        factory.setUsername("root");
        factory.setPassword("root");

        Connection connection = factory.newConnection(); // 创建连接
        Channel channel = connection.createChannel(); // 创建信道
        // 创建一个 type="direct" 持久化 、非自动删除的交换器
        channel.exchangeDeclare(EXEHANGE_NAME, "direct", true, false, null);
        //创建一个持久化、非排他的，非自动删除的队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 将交换器与队列通过路由建绑定
        channel.queueBind(QUEUE_NAME, EXEHANGE_NAME, ROUTING_KEY);
        // 发送一条持久化的消息
        String message = "Hello World! " + LocalDateTime.now();
        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
//        // 持久化消息
//        builder.deliveryMode(2);
//        // 设置 TTL
//        builder.expiration("60000");
//        builder.contentType("text/plain");
        channel.basicPublish(EXEHANGE_NAME, ROUTING_KEY, true, builder.build(), message.getBytes(StandardCharsets.UTF_8));
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange,
                                     String routingKey, AMQP.BasicProperties properties,
                                     byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("返回： " + msg);
            }
        });
        channel.close();
        connection.close();

    }

}
